package com.rtline.business.ratelimit;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class FixedWindowRateLimitStrategy implements RateLimitStrategy {

    //key:资源名称  value:对此接口的调用次数
    private final ConcurrentHashMap<String, AtomicInteger> requestCountMap = new ConcurrentHashMap<>();

    //key:资源名称  value:最后一次登录时间
    private final ConcurrentHashMap<String, Long> lastResetTimeMap = new ConcurrentHashMap<>();

    @Override
    public boolean isAllowed(String resource, int limit, long period) {
        AtomicInteger counter = requestCountMap.get(resource);
        if (counter == null) {
            counter = new AtomicInteger(0);
            requestCountMap.put(resource, counter);
            lastResetTimeMap.put(resource, System.currentTimeMillis());
        }

        long currentTime = System.currentTimeMillis();
        long lastResetTime = lastResetTimeMap.get(resource);

        if (currentTime - lastResetTime >= period * 1000) {
            //超过窗口时间，此数置为0
            counter.set(0);
            lastResetTimeMap.put(resource, currentTime);
        }

        if (counter.incrementAndGet() > limit) {
            counter.decrementAndGet();
            return false;
        }

        return true;
    }
}
